package com.project.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.project.bean.StudentBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

public class JsonServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        List<StudentBean> stuList= List.of(
                new StudentBean(1,"张三","13519636348", LocalDate.parse("2000-09-12")),
                new StudentBean(2,"李四","13515432348", LocalDate.parse("2001-09-12")),
                new StudentBean(3,"王五","13519266348", LocalDate.parse("2000-12-01")));

        ObjectMapper om = new ObjectMapper();
        //支持java时间的模块
        om.registerModule(new JavaTimeModule());
        //先转换成json格式
//        String jsonStr = om.writeValueAsString(stuList);
//        resp.getWriter().print(jsonStr);

        om.writeValue(resp.getWriter(),stuList);


    }
}
